package org.example.im.server.handler.impl.biz;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import org.example.im.bean.protocol.CommandType;
import org.example.im.bean.protocol.request.ListGroupMemberRequestPacket;
import org.example.im.bean.protocol.response.ListGroupMemberResponsePacket;
import org.example.im.bean.session.Session;
import org.example.im.common.util.SessionUtil;
import org.example.im.server.handler.ServerHandler;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author dingrui
 * @since 2022/2/12
 * @description 群成员
 */
@Component
public class ListGroupMemberHandler extends SimpleChannelInboundHandler<ListGroupMemberRequestPacket> implements ServerHandler {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ListGroupMemberRequestPacket request) throws Exception {
        // 群
        String groupId = request.getGroupId();
        if (Objects.isNull(groupId)) return;
        ChannelGroup channelGroup = SessionUtil.getChannelGroupByGroupId(groupId);
        if (Objects.isNull(channelGroup)) return;
        // 群成员
        List<Session> members = channelGroup.stream().map(SessionUtil::getSession).collect(Collectors.toList());
        ListGroupMemberResponsePacket response = ListGroupMemberResponsePacket.builder().groupId(groupId).sessionList(members).build();
        ctx.writeAndFlush(response);
    }

    @Override
    public CommandType genType() {
        return CommandType.LIST_GROUP_MEMBER_REQUEST;
    }
}
